<?php

class Service extends CI_Controller {

    function __construct() {
        parent::__construct();
        $level_id = $this->session->userdata('logged_in');
        if ($level_id['level_id'] == null) {
            redirect('user/login', 'refresh');
        }
        if ($level_id['level_id'] == 0) {
            redirect('user', 'refresh');
        }
		
    }

	function index() {
        $crud = new grocery_CRUD();
		
        $crud->set_table('service');
		$crud->set_relation('service_type_id', 'service_type', 'service_type_name',array('deleted' => 'No'));
		//$crud->where('service_type.deleted', 'No');
		//$crud->where('service.service_type_id', 'service_type.service_type_id');
		$crud->where('service.deleted', 'No');
		$crud->add_fields('service_code', 'service_name', 'service_type_id', 'service_buy_price', 'service_sell_price', 'service_qty', 'service_uom');
		$crud->edit_fields('service_code', 'service_name', 'service_type_id', 'service_buy_price', 'service_sell_price', 'service_qty', 'service_uom');
        $crud->required_fields('service_code', 'service_name', 'service_type_id', 'service_buy_price', 'service_sell_price', 'service_qty', 'service_uom');
        $crud->columns('service_code', 'service_name', 'service_type_id', 'service_buy_price', 'service_sell_price', 'service_qty', 'service_uom');
		
		
		
        $crud->display_as('service_code', 'Service Code');
        $crud->display_as('service_name', 'Name');
        $crud->display_as('service_type_id', 'Type');
		$crud->display_as('service_buy_price', 'Buy Price');
        $crud->display_as('service_sell_price', 'Sell Price');
		$crud->display_as('service_qty', 'Quantity');
		$crud->display_as('service_uom', 'Unit Of Measure');
        $crud->set_subject('Service');
		
		$crud->callback_column('service_buy_price', array($this, 'formatRupiah'));
		$crud->callback_column('service_qty', array($this, 'point_to_comma'));
        $crud->callback_field('service_qty', array($this, 'formatQtyField'));
        $crud->callback_field('service_buy_price', array($this, 'formatBuyField'));
        $crud->callback_column('service_sell_price', array($this, 'formatRupiah'));
        $crud->callback_field('service_sell_price', array($this, 'formatSellField'));
		$crud->callback_before_insert(array($this, 'cb_before_service'));
		$crud->callback_before_update(array($this, 'cb_before_service'));
		
		$crud->callback_add_field('service_code',array($this,'field_code'));
		
		$crud->callback_delete(array($this, 'deleted'));
		
		$crud->callback_after_update(array($this, 'get_id'));
		$crud->callback_after_insert(array($this, 'get_id'));
		$output = (array) $crud->render();
        $output['title'] = 'Service List';

        $this->load->template('service/index', $output);
    }
	
	function field_code(){
		$query = "select max(service_code) as max from service";
		$result = $this->db->query($query)->row();
		$string = (int) $result->max+1;
		return '<input type="text" maxlength="4" value="'.$string.'" name="service_code" style="width:auto">';
	
	}
	
	function cb_before_service($post) {
		$post['service_qty'] = $this->load->comma_to_point($post['service_qty']);
		$post['service_buy_price'] = $this->load->comma_to_point($post['service_buy_price']);
		$post['service_sell_price'] = $this->load->comma_to_point($post['service_sell_price']);
		
		return $post;
	}
	
	
	function get_id($post_array, $primary_key)
	{
	$sess=$this->session->userdata('logged_in');
	$this->db->update('service', array('last_modifier' => $sess['user_id']), array ('service_id' => $primary_key));
	
	}
	
	function deleted($primary_key){
	$sess=$this->session->userdata('logged_in');
	return $this->db->update('service', array('deleted' => 'Yes' , 'last_modifier' => $sess['user_id']), array ('service_id' => $primary_key));
	}

    function type() {
        $crud = new grocery_CRUD();
		$crud->where('deleted','No');
		
        $crud->set_table('service_type');
        $crud->display_as('service_type_name', 'Service Type');

        $crud->set_subject('Service Type');

        $crud->required_fields('service_type_code', 'service_type_name', 'service_type_desc');
		
		$crud->unset_edit_fields('service_type_id', 'last_modifier', 'last_modified', 'deleted');
		$crud->unset_add_fields('service_type_id', 'last_modifier', 'last_modified', 'deleted');
		$crud->callback_add_field('service_type_code',array($this,'field_code1'));
		$crud->callback_after_update(array($this, 'after_edit'));
		$crud->callback_delete(array($this, 'after_delete'));
		$crud->callback_after_insert(array($this, 'after_insert'));
		
        $crud->columns('service_type_code', 'service_type_name','service_type_desc');
        $crud->display_as('service_type_code', 'Service Type Code');
        $crud->display_as('service_type_name', 'Service Type Name');
        $crud->display_as('service_type_desc', 'Description');
		
		

		$level_id = $this->session->userdata('logged_in');
		if($level_id['level_id']== 3){
			$crud->unset_delete();
			$crud->unset_edit();
			
			$output = (array) $crud->render();
			$output['title'] = 'Service Type List';
			$this->load->template('service/servicetype', $output);
		} else {
			$output = (array) $crud->render();
			$output['title'] = 'Service Type List';
			$this->load->template('service/servicetype', $output);
			
		}
    }
	
	function order() {
		 $crud = new grocery_CRUD();

        $crud->set_table('service_order');
		$crud->set_relation('payment_id', 'payment_type', 'payment_name');
		//$crud->where('service_order.deleted', 'No');
        $crud->columns('serv_ord_id', 'serv_ord_time', 'guest', 'serv_ord_total', 'serv_ord_paid', 'bill_type', 'payment_id', 'room_name', 'serv_ord_desc', 'actions');
        //$crud->columns('service_id', 'service_name', 'service_type_id', 'service_price');
		$crud->order_by('serv_ord_time','desc');
		
        $crud->display_as('serv_ord_id', 'Order Code');
        $crud->display_as('serv_ord_time', 'Order Time');
        $crud->display_as('serv_ord_total', 'Grand Total');
        $crud->display_as('serv_ord_paid', 'Paid');
        $crud->display_as('payment_id', 'Payment Type');
        $crud->display_as('room_name', 'Room Name');
        $crud->display_as('serv_ord_desc', 'Order Description');

        $crud->set_subject('Order');
		
        $crud->callback_column('serv_ord_total', array($this, 'formatRupiah'));
        $crud->callback_column('serv_ord_paid', array($this, 'formatRupiah'));
        $crud->callback_column('actions', array($this, 'action_order'));
		$crud->callback_column('guest', array($this, 'cb_guest'));
        //$crud->callback_field('service_price', array($this, 'formatPriceField'));
		$crud->unset_operations();

        $output = (array) $crud->render();
        $output['title'] = 'Service Order';

        $this->load->template('service/serviceorder', $output);
	}
	
	
	function cb_guest($pk, $row) {
		$this->load->model('service_model');
		
		$guest = $this->service_model->get_guest($row->resv_id)->row_array();
		
		if($guest){
			return $guest['guest_name'];
		}
		else {
			return '-- Guest --';
		}
	}
	
	function add_order($resv_id = null) {
		$this->load->model('payment_model');
		$this->load->model('reservation_model');
		
		$data['css_files'] = false;
        $data['title'] = 'Add Order';
		$data['paym_type'] = $this->payment_model->select_all()->result_array();
		$data['resv_id'] = $resv_id;
		$data['resv'] = $this->reservation_model->get_guest($resv_id)->row_array();

        $this->load->template('service/add_order', $data);
	}
	
	function cancel_order($id){
		$sess = $this->session->userdata('logged_in');
		$this->db->update('service_order', array('deleted'=>'Yes', 'last_modifier'=>$sess['user_id'], 'serv_ord_desc'=>'Cancelled'), 'serv_ord_id ='.$id);
		$this->db->update('service_detail', array('deleted'=>'Yes', 'last_modifier'=>$sess['user_id']), 'serv_ord_id ='.$id);
		redirect('service/order');
	}
	
	function save_order($resv_id = null) {
		$this->load->model('service_model');
		//var_dump($this->input->post());
		$logged_in = $this->session->userdata('logged_in');
		$serv_ord = array(
			'serv_ord_total' => $this->input->post('grand-total'),
			'ppn_tax' => $this->comma_to_point($this->input->post('ppn-tax')),
			'service_tax' => $this->comma_to_point($this->input->post('serv-tax')),
			'room_name' => $this->input->post('room-name'),
			'serv_ord_desc' => $this->input->post('ord-desc'),
			'serv_ord_time' => $this->std_time($this->input->post('ord-time')),
			'bill_type' => $this->input->post('bill-type'),
			'user_id' => $logged_in['user_id'],
			'last_modifier' => $logged_in['user_id']
		);
		
		if($this->input->post('disc') == 'percent') {
			$serv_ord['discount_percent'] = $this->comma_to_point($this->input->post('disc-percent'));
		}
		else if($this->input->post('disc') == 'nominal') {
			$serv_ord['discount_nominal'] = $this->comma_to_point($this->input->post('disc-nominal'));
		}
		else {
			$serv_ord['discount_percent'] = null;
			$serv_ord['discount_nominal'] = null;
		}
		
		if($this->input->post('bill-type') == 'Reservation') {
			$serv_ord['resv_id'] = $this->input->post('resv-id');
		} else {
			$serv_ord['serv_ord_paid'] = $this->comma_to_point($this->input->post('paid'));
			$serv_ord['payment_id'] = $this->input->post('paym-type');
			$serv_ord['special_code'] = $this->input->post('card-code');
		}
		
		$id_serv_ord = $this->service_model->insert_service_order($serv_ord);
		if($id_serv_ord > 0) {
			$servs_id = $this->input->post('serv-id');
			$servs_qty = $this->input->post('serv-qty');
			$servs_price = $this->input->post('serv-price');
			for($i=0;$i<count($servs_id);$i++) {
				$serv_det = array(
					'serv_ord_id' => $id_serv_ord,
					'service_id' => $servs_id[$i],
					'serv_det_price' => $servs_price[$i],
					'serv_det_qty' => $this->comma_to_point($servs_qty[$i]),
					'last_modifier' => $logged_in['user_id']
				);
				$this->service_model->insert_service_detail($serv_det);
			}
		}
		
		if($resv_id != null && $this->input->post('bill-type') == 'Reservation') redirect('reservation/service/'.$resv_id);
		else redirect('service/order');
	}
	
	function auto_suggestion() {
		
		$this->load->model('service_model');
	
		$services = $this->service_model->auto_suggestion();
				
		$term = trim(strip_tags($_GET['term']));
		$matches = array();
		
		foreach($services->result_array() as $s){
			if(stripos($s['service_name'], $term) !== false){
				$s['value'] = $s['service_name'];
				$s['label'] = '['.$s['service_type_name'].'] ['.$s['service_name'].'] ['.$s['service_uom'].'] ['.$this->formatRupiah($s['service_sell_price']).']';
				$matches[] = $s;
			}
		}
		 
		$matches = array_slice($matches, 0, 10);
		echo json_encode($matches);
	}
	
	function guest_search($time) {
        $crud = new grocery_CRUD();
		$this->load->model('reservation_model');
		
		$time = new DateTime($this->std_time(urldecode($time)));
		$date = date_format($time, 'Y-m-d');
		
		$resvs = $this->reservation_model->get_resv_in_time($date)->result_array();       
	   
		$crud->set_table('reservation');
		$crud->set_subject('Guest');
		$crud->set_relation('guest_id', 'guest', '{guest_name} ({guest_ktp})');
		
		foreach($resvs as $resv){
			$crud->or_where('reservation.resv_id',$resv['resv_id']);
		}
		if(count($resvs) == 0){
			$crud->where('reservation.resv_id','-1');
		}
		
		$crud->columns('guest_id', 'Room Number', 'Action');
		$crud->unset_operations();

        $crud->display_as('guest_id', 'Name & Identity Card');

        $crud->callback_column('Room Number', array($this, 'guest_room'));
        $crud->callback_column('Action', array($this, 'choose_guest'));

        $output = $crud->render();
        $this->load->view('service/guestsearch', $output);
    }
	
	function std_time($datetime) {
		if($datetime != null || $datetime != '') {
			$datetime = explode(' ', $datetime);
			$date = $datetime[0];
			$time = $datetime[1];
			$date = explode('-', $date);
			$datetime = $date[2].'-'.$date[1].'-'.$date[0].' '.$time;
		}
		
		return $datetime;
	}
	
	function comma_to_point($number) {
		return str_replace(',','.',str_replace('.','',$number));
	}
	

    function formatRupiah($value) {
		if($value != null) {
			return 'Rp  ' . number_format($value, 2, ',', '.');
		}
		else {
			return $value;
		}
    }

    function formatPriceField($value = '') {
        return 'Rp <input type="number" maxlength="10" value="' . $value . '" name="service_price" style="width:auto"> ,00';
    }
	
	function formatBuyField($value = '') {
        return 'Rp <input class="rp" type="text" value="' . $value . '" name="service_buy_price" style="width:auto">';
    }
	
	function formatSellField($value = '') {
        return 'Rp <input class="rp" type="text" value="' . $value . '" name="service_sell_price" style="width:auto">';
		
    }
	
	function formatQtyField($value = '') {
        return '<input class="qty" type="text" value="' . $value . '" name="service_qty" style="width:auto">';
		
    }
	
	function after_edit($post, $primary_key){
		$level_id = $this->session->userdata('logged_in');
		$this->db->update('service_type', array('last_modifier'=>$level_id['user_id']),array('service_type_id'=>$primary_key));
	}
	
	function after_delete($primary_key){
		$level_id = $this->session->userdata('logged_in');
		$this->db->update('service_type', array('deleted'=>'Yes', 'last_modifier'=>$level_id['user_id']),array('service_type_id'=>$primary_key));
		$this->db->update('service', array('last_modifier'=>$level_id['user_id'], 'deleted'=>'Yes'), array('service_type_id'=>$primary_key));
	}
	
	function after_insert($post, $primary_key){
		$level_id = $this->session->userdata('logged_in');
		$this->db->update('service_type', array('last_modifier'=>$level_id['user_id']),array('service_type_id'=>$primary_key) );
	}
	
	function field_code1(){
		$query = "select max(service_type_code) as max from service_type";
		$result = $this->db->query($query)->row();
		$string = (int) $result->max+1;
		return '<input type="text" maxlength="4" value="'.$string.'" name="service_type_code" style="width:auto">';
	}
	
	function point_to_comma($number) {
		return $this->load->point_to_comma($number);
	}
	
	function link_detail($pk, $row){
		 return site_url('service/detail_order/'.$pk);
	}
	
	function action_order($pk, $row){
		$this->load->model('service_model');
		$btn = '';
		if($row->bill_type == 'Reservation' && $row->deleted == 'No'){
			if($this->service_model->is_cancelable($row->resv_id)){
				$btn .= '<a style="color:white" class="btn btn-small btn-danger" onclick="var a=window.confirm(\'Are you sure that you want to cancel this order?\');if(!a)return false;" href="' . base_url() . 'service/cancel_order/' . $row->serv_ord_id . '">Cancel</a>';
			}
			
		}
		if($row->bill_type == 'On Spot'){
			$btn .= '<a style="color:white" class="btn btn-small btn-primary" href="' . base_url() . 'report/information_service/' . $row->serv_ord_id . '">Print Invoice</a>';
		}
				
		return $btn;
	}
	
	function choose_guest($value, $row) {
		$this->load->model('reservation_model');
		$resv_guest = $this->reservation_model->get_resv_guest($row->resv_id)->row();
        return '<a style="color:white" class="btn btn-primary btn-small" href="javascript:void(0)" onclick="choose(\'' . $row->resv_id . '\', \'' . $resv_guest->guest_name . '\')">Choose</a>';
    }
	
	function guest_room($value, $row) {
		$this->load->model('reservation_model');
		$resv_rooms = $this->reservation_model->get_resv_room($row->resv_id)->result();
		$rooms = '';
		
		foreach($resv_rooms as $room){
			$rooms .= $room->room_number.' ';
		}
		return $rooms;
	}
	
}